<script setup lang="ts">
import { reactive, ref } from 'vue';
import { getCurrentInstance, showModal, login } from '@tarojs/taro';
import JSEncrypt from 'jsencrypt';
import { cloneDeep } from 'lodash';
import { setStorage, setStorageSync, reLaunch, showLoading, hideLoading } from '@tarojs/taro';
import IMG_BLUE_BG from '/@/assets/image/bg/blue-bg.png';
import { APP_EDITION } from '/@/common/constant';
import { USER_LOGIN } from '/@/api/modules/base/user';
import { WX_USER_LOGIN } from '/@/api/modules/wechat/index';
import { GET_PUBLIC_KEY } from '/@/api/modules/open-api/auth';
import { formRules } from './state';

const loginFormRef = ref();
const RSA = new JSEncrypt();

/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as {
  /**
   * 前往页面
   */
  toPage?: string;
};

const state = reactive<{
  /**
   * 应用版本
   */
  appEdition: keyof typeof APP_EDITION;
  /**
   * taro应用环境
   */
  taroEnv: string;
}>({
  appEdition: (process.env.APP_EDITION as keyof typeof APP_EDITION) || 'default',
  taroEnv: process.env.TARO_ENV,
});

const formState = reactive<BaseUserLoginApi.UserLoginReq>({
  account: '',
  password: '',
  loginType: 1,
});

/**
 * @function 确认登录
 */
function submit() {
  loginFormRef.value.validate().then(({ valid }) => {
    if (!valid) return;
    showLoading();

    GET_PUBLIC_KEY({ secretTag: 'ib_platform_pub' }).then((res1) => {
      const _form = cloneDeep(formState);
      RSA.setPrivateKey(res1.publicKey);
      _form.password = RSA.encrypt(`${Date.now()}${formState.password}`) as string;

      USER_LOGIN(_form)
        .then((res) => {
          setStorage({
            key: 'token',
            data: res.token,
            success: () => {
              formState.account = '';
              formState.password = '';
              setStorageSync('loginType', 'default');
              hideLoading();
              reLaunch({
                url: params.toPage ? decodeURIComponent(params.toPage) : '/pages/index/index',
              });
            },
          });
        })
        .catch((err) => {
          hideLoading();
          showModal({
            content: err.comResp.tip,
            showCancel: false,
          });
        });
    });
  });
}

/**
 * @function 微信登录
 */
function wxLogin() {
  showLoading();

  login().then((res1) => {
    WX_USER_LOGIN({
      code: res1.code,
    }).then((res2) => {
      setStorage({
        key: 'token',
        data: res2.token,
        success: () => {
          formState.account = '';
          formState.password = '';
          setStorageSync('loginType', 'default');
          hideLoading();
          reLaunch({
            url: '/pages/index/index',
          });
        },
      });
    });
  });
}
</script>

<template>
  <view class="user-login app-page--1">
    <view class="user-login__header">
      <view class="user-login__header__container">
        <view class="user-login__title">欢迎使用，</view>
        <view class="user-login__title--sub">
          {{
            {
              default: '龙港市人民医院数智管控平台',
              hgy: '慧管用保障平台',
              'jinhua-police-service': '掌上运维管理',
              'can-nang-third-hospital': '航天云筑智慧医院后勤',
            }[state.appEdition]
          }}
        </view>
      </view>
      <image class="user-login__header-bg" mode="widthFix" :src="IMG_BLUE_BG" />
    </view>
    <view class="user-login__wrapper">
      <nut-form
        :model-value="formState"
        :rules="formRules"
        class="user-login__form"
        ref="loginFormRef"
      >
        <view class="user-login__form-item-label">用户名</view>
        <nut-form-item prop="account" error-message-align="left">
          <nut-input v-model="formState.account" placeholder="请输入用户名" type="text" clearable />
        </nut-form-item>
        <view class="user-login__form-item-label">密码</view>
        <nut-form-item prop="password" error-message-align="left">
          <nut-input
            v-model="formState.password"
            placeholder="请输入密码"
            type="password"
            clearable
          />
        </nut-form-item>
      </nut-form>
      <nut-button class="user-login__login-btn" type="info" block @click="submit()">
        登录
      </nut-button>
      <nut-button
        v-if="state.taroEnv === 'weapp'"
        class="user-login__wx-login-btn"
        type="success"
        block
        @click="wxLogin()"
      >
        微信登录
      </nut-button>
      <!-- <nut-button class="user-login__to-code-login-btn" block>验证码登录</nut-button> -->
      <view class="user-login__to-other-login-wrapper">
        <view class="user-login__to-other-login-wrapper--left">
          <text
            @click="
              reLaunch({
                url: `/pages/user/login-phone/index?toPage=${
                  params.toPage || '/pages/index/index'
                }`,
              })
            "
          >
            短信验证码登录
          </text>
        </view>
        <view class="user-login__to-other-login-wrapper--right">
          <text
            @click="
              reLaunch({
                url: `/pages/user/login-now/index?toPage=${params.toPage || '/pages/index/index'}`,
              })
            "
          >
            使用一键登录
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
